package uit.edu.vn.Activity;



import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.WebService;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class LoginActivity extends MyActivity {
        
        public static String User;
        public static String Pass;
    	private EditText edt_IP;
    	private ProgressDialog loadingLoginDialog;
        public static int UserID;
        private Handler myHandler = new Handler();
        private CheckBox check;
        private Button btn_login, btn_registry;
        private EditText edt_User,edt_Pass;
        private static final String     STRING_NAME_USERSETTING = "USER REFERENCES";
        private SharedPreferences ShareRef  = null;
        public static String ipAddress = null;
                               
        public static int getUserID() {
                return UserID;
        }
        
        public static void setUserID(int id){
                UserID = id;
        }

        public static void setUsername(String username) {
                User = username;
        }
        public static String getUsername() {
                return User;
        }       

        public static void setPassword(String password) {
                Pass = password;
        }
        public static String getPassword() {
                return Pass;
        }       
                                    
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            ipAddress = getSetting("address");
            System.out.println("ipAddress login0: "+ipAddress);
            if(ipAddress.equals("")){
            	saveSetting("address", "192.168.1.21:8080");
            	ipAddress = getSetting("address");
            	System.out.println("ipAddress login1: "+ipAddress);
            }
            System.out.println("ipAddress login2: "+ipAddress);
            check = (CheckBox)findViewById(R.id.checkbox_Save);
            check.setChecked(true);
            btn_login = (Button)findViewById(R.id.btn_Login);
            btn_registry = (Button)findViewById(R.id.btn_Registry);
            edt_User = (EditText)findViewById(R.id.edt_login);
            edt_Pass = (EditText)findViewById(R.id.edt_password);
            edt_IP= new EditText(this);
           
            User = getSetting("username");
            Pass = getSetting("password");
            
            //kiem tra thong tin username, password cho lan dang nhap sau
            if(!User.equals("") && !Pass.equals("")){
                try {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            //su kien dang nhap he vao tai khoan nguoi dung
            btn_login.setOnClickListener( new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
		              final ProgressDialog pdialog = showProgress("Đang đăng nhập hệ thống", "Vui lòng đợi trong giây lát...", R.drawable.ic_lock, false);
		                final Thread threadLogin = new Thread() {
		                public void run() {
		                    try {
		                        final String username = edt_User.getText().toString();
		                        final String password = edt_Pass.getText().toString();
		                        if (username.equals("") || password.equals("")) {
		                            myHandler.post(new Runnable() {
		                                @Override
		                                public void run() {
		                                	showToast("Vui lòng điền đầy đủ thông tin đăng nhập!");
		                                	pdialog.dismiss();
		                                }
		                        });
		                        } else {
//		                        	WebService web = new WebService();
			                            String msg = WebService.checkLogin(username, password);
			                            UserID = Integer.parseInt(msg.trim());
			                            if (UserID == -1) {
			                                myHandler.post(new Runnable() {
			                                    @Override
			                                    public void run() {
			                                        showToast("Sai tên đăng nhập hoặc mật khẩu!");
			                                    	pdialog.dismiss();
			                                    }
			                                });
			                            } else {
			                                User = username;
			                                Pass = password;
			                                final boolean chk = check.isChecked();
			                                System.out.println("id of user: "+UserID);
			                                myHandler.post(new Runnable() {
			                                    @Override
			                                    public void run() {
			                                        if (chk) {
			                                            saveSetting("password", password);
			                                            saveSetting("username", username);
			                                            saveSetting("userid", String.valueOf(UserID));  
			                                            saveSetting("address", edt_IP.getText().toString().trim());
			                                        } else {
			                                            saveSetting("password", "");
			                                            saveSetting("username", "");
			                                            saveSetting("userid", String.valueOf(UserID));
			                                            saveSetting("address", edt_IP.getText().toString().trim());
			                                        }
			                                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			                                        startActivity(intent);       
			                                    	pdialog.dismiss();
			                                    }                                           
			                                });                             
			                            }
		                        	}
		                        } catch (final Exception e) {
		                            myHandler.post(new Runnable() {
		                                @Override
		                                public void run() {
		                                    showToast("Đăng nhập thất bại! Vui lòng kiểm tra lại địa chỉ máy chủ");
		                                	pdialog.dismiss();
		                                	System.out.println(e.toString());
		                                	e.printStackTrace();
		                                }                                               
		                            });                 
		                        }                       
		                }                       
		            };
		            threadLogin.start();
				}
			});
            
            //su kien nhat nut dang ky tai khoan nguoi dung
            btn_registry.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
		            Intent intent = new Intent(LoginActivity.this, RegistryActivity.class);
		            
		            startActivity(intent);
		            Log.d("tag","Chay intent");
				}
			});
        }        
        public static String getIPAddress(){           
       	 return ipAddress;
        }
        //lay thong tin tu SharedPreferences len
      public String getSetting(String key) {
          ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
          return ShareRef.getString(key, "");
      }          
    public class BackGroundTask extends AsyncTask<Void, Void, Void>
    {
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    		loadingLoginDialog.show();
    	}
    	@Override
    	protected Void doInBackground(Void... params) {
    		// TODO Auto-generated method stub
    		//String msg = WebService.checkLogin(username, password);
    		return null;
    	}
    	@Override
    	protected void onPostExecute(Void result) {
    		// TODO Auto-generated method stub
    		super.onPostExecute(result);
    	}
    }
    public ProgressDialog showProgress(String title, String msg, int icon, boolean cancelable) {
    		ProgressDialog pdialog = new ProgressDialog(this);
    		if (title != null) {
    			pdialog.setTitle(title);
    		}
    		if (msg != null)
    			pdialog.setMessage(msg);
    		if (icon != -1) {
    			pdialog.setIcon(icon);
    		}
    		pdialog.setCancelable(cancelable);
    		pdialog.show();
    		return pdialog;
    	}
 //--------------------xu ly menu ----------------------------
   	 public boolean onCreateOptionsMenu(Menu menu) 
   	 {
   	    	// TODO Auto-generated method stub
   	    	//return super.onCreateOptionsMenu(menu);
   	    	new MenuInflater(getApplicationContext()).inflate(R.menu.login_option_menu, menu);
   		    return super.onCreateOptionsMenu(menu);
   	 }
   	 @Override
   	 public boolean onOptionsItemSelected(MenuItem item) 
   	 {
   		 // TODO Auto-generated method stub
   		 switch(item.getItemId())
 	    {
 	    	case R.id.menu_login_config:
 	    		showIpAddressDialog("Thông báo", "Nhập địa chỉ máy chủ", new android.content.DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					    ipAddress=edt_IP.getText().toString().trim();
						saveSetting("address", ipAddress);
						System.out.println("ipAddress login2 : "+ipAddress);
					}
				});					
 	    		
 	    		return true;

 	    	case R.id.menu_login_info:
 	    		showConfirmDialog("Giới Thiệu ", getResources().getString(R.string.title_info),  new android.content.DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						
						///////////
						/*
						final ProgressDialog pdialog = showProgress("Đang đăng nhập hệ thống", "Vui lòng đợi trong giây lát...", R.drawable.ic_lock, false);
		                final Thread threadLogin = new Thread() {
		                public void run() {
		                    try {
		                        final String username = edt_User.getText().toString();
		                        final String password = edt_Pass.getText().toString();
		                        if (username.equals("") || password.equals("")) {
		                            myHandler.post(new Runnable() {
		                                @Override
		                                public void run() {
		                                	showToast("Vui lòng điền đầy đủ thông tin đăng nhập!");
		                                	pdialog.dismiss();
		                                }
		                        });
		                        } else {
			                            String msg = WebService.checkLogin(username, password);
			                            UserID = Integer.parseInt(msg.trim());
			                            if (UserID == -1) {
			                                myHandler.post(new Runnable() {
			                                    @Override
			                                    public void run() {
			                                        showToast("Sai tên đăng nhập hoặc mật khẩu!");
			                                    	pdialog.dismiss();
			                                    }
			                                });
			                            } else {
			                                User = username;
			                                Pass = password;
			                                final boolean chk = check.isChecked();
			                                System.out.println("id of user: "+UserID);
			                                myHandler.post(new Runnable() {
			                                    @Override
			                                    public void run() {
			                                        if (chk) {
			                                            saveSetting("password", password);
			                                            saveSetting("username", username);
			                                            saveSetting("userid", String.valueOf(UserID));  
			                                        } else {
			                                            saveSetting("password", "");
			                                            saveSetting("username", "");
			                                            saveSetting("userid", String.valueOf(UserID));
			                                        }
			                                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			                                        startActivity(intent);       
			                                    	pdialog.dismiss();
			                                    }                                           
			                                });                             
			                            }
		                        	}
		                        } catch (final Exception e) {
		                            myHandler.post(new Runnable() {
		                                @Override
		                                public void run() {
		                                    showToast("Đăng nhập thất bại!");
		                                	pdialog.dismiss();
		                                }                                               
		                            });                 
		                        }                       
		                }                       
		            };
		            threadLogin.start();
						 */
						
						//showToast("log me in");
						
			            //////

						dialog.dismiss();

					}
				});					
 	    		
 	    		return true; 	    			 	    		
 	    }
   		return false;
   	}
     public AlertDialog showIpAddressDialog(String title, String msg, android.content.DialogInterface.OnClickListener yesClick){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.ic_error);
			edt_IP= new EditText(this);
			edt_IP.setSingleLine();
			ipAddress = getSetting("address");
			if(!ipAddress.equals(""));
				edt_IP.setText(ipAddress);
		    builder.setView(edt_IP);
			if(title!=null) builder.setTitle(title);
			if(msg!=null) builder.setMessage(msg);
			return builder.setPositiveButton(getResources().getString(R.string.txt_Yes), yesClick).setNegativeButton(getResources().getString(R.string.txt_No), new android.content.DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					//luu lai dia chi ip 
					saveSetting("address", edt_IP.getText().toString().trim());
					System.out.println("ipAddress dialog login: "+ipAddress);
					dialog.dismiss();
				}
			}).show();
		}
     

    
}
